package recite.word.service.base.util.transaction;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @program: recite-word-back
 * @description:
 * @author: Mr.lin
 * @create: 2023-01-02 22:08
 **/

@Slf4j
@Component
public class TransactionUtil {

	@Resource
	private PlatformTransactionManager transactionManager;

	public boolean transactional(Supplier<Boolean> supplier) {
		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
		try {
			Boolean res = supplier.get();
			if (Objects.isNull(res) || !res) {
				transactionManager.rollback(status);
				return false;
			} else {
				transactionManager.commit(status);
				return true;
			}
		} catch (Exception e) {
			log.error("编程式事务业务异常回滚", e);
			transactionManager.rollback(status);
			return false;
		}
	}
}
